package com.dense.kuiniu.shelfcard.card.iccard;

import com.rfid.api.ADReaderInterface;
import com.rfid.api.ISO14443AInterface;
import com.rfid.api.ISO14443ATag;
import com.rfid.def.ApiErrDefinition;
import com.rfid.def.RfidDef;

import java.math.BigInteger;

/**
 * @author Administrator
 * @date 2021/3/4
 */
public class HFCardReader implements ICardReader {
    private ADReaderInterface reader = new ADReaderInterface();

    public HFCardReader() {
        open();
    }

    @Override
    public String readCard() {
        return read();
    }

    private boolean open() {
        String conStr = "RDType=RL8000;CommType=COM;ComPath=/dev/ttyXRUSB1;Baund=38400;Frame=8E1;Addr=255";
        int ret = reader.RDR_Open(conStr);
        return ret == ApiErrDefinition.NO_ERROR;
    }

    public String read() {
        byte[] mAntId = null;
        String cardNo = "";
        Object hInvenParamSpecList = ADReaderInterface
                .RDR_CreateInvenParamSpecList();
        ISO14443AInterface.ISO14443A_CreateInvenParam(hInvenParamSpecList,
                (byte) 0);
        int ret = reader.RDR_TagInventory(RfidDef.AI_TYPE_NEW,
                mAntId, 0, hInvenParamSpecList);
        if (ret == ApiErrDefinition.NO_ERROR) {
            Object tagReport = reader
                    .RDR_GetTagDataReport(RfidDef.RFID_SEEK_FIRST);
            if (tagReport != null) {
                ISO14443ATag tagData = new ISO14443ATag();
                ISO14443AInterface.ISO14443A_ParseTagDataReport(tagReport, tagData);
                int len = tagData.uid.length;
                byte[] copy = new byte[len];
                for (int i = 0; i < len; i++) {
                    copy[i] = tagData.uid[len - i - 1];
                }
                cardNo = new BigInteger(1, copy).toString(10);
                if (cardNo.length() < 10) {
                    //todo 规则待定
                    cardNo = "0" + cardNo;
                }
            }
        }
        return cardNo;
    }
}